# Multi-stage Dockerfile for mall-admin
# Stage 1: Build environment with Maven and JDK
FROM openjdk:8-jdk-alpine AS builder

# Install Maven
RUN apk add --no-cache curl tar bash \
    && mkdir -p /usr/share/maven /usr/share/maven/ref \
    && curl -fsSL -o /tmp/apache-maven.tar.gz https://archive.apache.org/dist/maven/maven-3/3.8.6/binaries/apache-maven-3.8.6-bin.tar.gz \
    && tar -xzf /tmp/apache-maven.tar.gz -C /usr/share/maven --strip-components=1 \
    && rm -f /tmp/apache-maven.tar.gz \
    && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

# Set Maven environment variables
ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"

# Set working directory
WORKDIR /app

# Copy pom files for dependency resolution and caching
COPY pom.xml .
COPY mall-common/pom.xml ./mall-common/
COPY mall-mbg/pom.xml ./mall-mbg/
COPY mall-security/pom.xml ./mall-security/
COPY mall-admin/pom.xml ./mall-admin/
COPY mall-demo/pom.xml ./mall-demo/
COPY mall-search/pom.xml ./mall-search/
COPY mall-portal/pom.xml ./mall-portal/

# Download dependencies for better caching
RUN mvn dependency:go-offline -B

# Copy source code
COPY . .

# Stage 2: Build dependency modules
FROM builder AS dependency-builder

# Build dependency modules first (mall-common, mall-mbg, mall-security)
RUN mvn clean install -pl mall-common,mall-mbg,mall-security -am -B -DskipTests

# Stage 3: Build mall-admin module
FROM dependency-builder AS app-builder

# Build mall-admin module
RUN mvn clean package -f mall-admin/pom.xml -B -DskipTests

# Stage 4: Runtime environment with JRE
FROM openjdk:8-jre-alpine AS runtime

# Install curl for health checks
RUN apk add --no-cache curl

# Create app user for security
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S appuser -G appgroup

# Set working directory
WORKDIR /app

# Copy the built JAR from the builder stage
COPY --from=app-builder /app/mall-admin/target/mall-admin-1.0-SNAPSHOT.jar app.jar

# Change ownership to app user
RUN chown -R appuser:appgroup /app

# Switch to non-root user
USER appuser

# Expose port 8080
EXPOSE 8080

# Set JVM options for container environment
ENV JAVA_OPTS="-Xms512m -Xmx1024m -Djava.security.egd=file:/dev/./urandom"

# Health check with enhanced monitoring
HEALTHCHECK --interval=30s --timeout=15s --start-period=90s --retries=5 \
    CMD curl -f http://localhost:8080/actuator/health/liveness || \
        curl -f http://localhost:8080/actuator/health || \
        curl -f http://localhost:8080/health/status || exit 1

# Start the application
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]